package com.xjtu.mybatisplus.web.controller;

import com.xjtu.mybatisplus.common.constant.MessageConstant;
import com.xjtu.mybatisplus.common.utls.JwtUtil;
import com.xjtu.mybatisplus.model.vo.comment.CommentsVo;
import com.xjtu.mybatisplus.service.ArticleService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.xjtu.mybatisplus.common.JsonResponse;
import com.xjtu.mybatisplus.service.CommentService;
import com.xjtu.mybatisplus.model.domain.Comment;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * 前端控制器
 *
 * @author lsong
 * @version v1.0
 * @since 2023-12-27
 */
@Controller
@RequestMapping("/api/comment")
public class CommentController {

    private final Logger logger = LoggerFactory.getLogger(CommentController.class);

    @Autowired
    private CommentService commentService;

    @Value("${jwt.user-token-name}")
    private String tokenName;

    /**
     * 描述：根据Id 查询
     */

    @GetMapping("/{articalId}")
    @ResponseBody
    public JsonResponse getComments(@PathVariable("articalId") Integer id){
        List<CommentsVo> commentsVos = commentService.getCommentByArticalId(id);
        return JsonResponse.success(commentsVos);
    }
    /**
     * 描述：根据Id删除
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResponse deleteById(@PathVariable("id") Long id,HttpServletRequest request) throws Exception {
        String token = request.getHeader(tokenName);
        if(token == "" || token == null){
            return JsonResponse.failure(MessageConstant.USER_NOT_LOGIN);
        }
        // 获取登陆的用户信息
        Long userId = JwtUtil.getFrontUserId(token);
        if(userId == null){
            return JsonResponse.failure(MessageConstant.USER_NOT_LOGIN);
        }
        commentService.deleteByCommentId(id,userId);
        return JsonResponse.success(null);
    }


    /**
     * 描述：根据Id 更新
     */
    @RequestMapping(value = "", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResponse updateComment(Comment comment) throws Exception {
        commentService.updateById(comment);
        return JsonResponse.success(null);
    }


    /**
     * 描述:创建Comment
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse create(@RequestBody Comment comment, HttpServletRequest request) throws Exception {

        boolean b = commentService.addComment(comment, request);
        if(!b){
           return JsonResponse.failure(MessageConstant.USER_NOT_LOGIN);
        }
        return JsonResponse.success(null);
    }

}

